package com.gmail.at.service.jpa;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.gmail.at.dao.TrainDAO;
import com.gmail.at.model.Train;
import com.gmail.at.service.TrainService;
import com.google.common.collect.Lists;

@Service("trainService")
@Repository
@Transactional
public class TrainServiceImpl implements TrainService {

	@Autowired
	private TrainDAO trainDAO;
	
	@Override
	@Transactional(readOnly=true)
	public List<Train> findAll() {
		return Lists.newArrayList(trainDAO.findAll());
	}

	@Override
	@Transactional(readOnly=true)
	public Train findById(Integer id) {
		return trainDAO.findOne(id);
	}

	@Override
	public Train save(Train train) {
		if (trainDAO.findByNumber(train.getTrainNumber()) == null) {
			return trainDAO.save(train);
		}
		return null;
	}

	@Override
	public String delete(Integer id) {
		Train train = this.findById(id);
		if (train != null) {
			trainDAO.delete(train);
			return "ok";
		}
		return "no";
	}
	
	@Transactional(readOnly=true)
	public Page<Train> findAllByPage(Pageable pageable) {
		return trainDAO.findAll(pageable);
	}

}
